const defaultPlugins = ['advlist', 'anchor', 'autolink', 'autoresize', 'autosave', 'charmap', 'code', 'codesample',
    'directionality', 'fullscreen', 'help', 'image', 'importcss', 'insertdatetime',
    'link', 'lists', 'media', 'nonbreaking', 'pagebreak', 'preview', 'quickbars', 'save', 'searchreplace',
    'table', 'visualblocks', 'visualchars', 'wordcount']

const defaultToolbar = 'undo redo | bold italic forecolor backcolor underline strikethrough lineheight | fontfamily fontsize blocks | ' +
    'alignleft aligncenter alignright alignjustify outdent indent | numlist bullist | print preview fullscreen restoredraft | ' +
    'cut copy paste pastetext removeformat | code blockquote anchor subscript superscript table image media | ' +
    'charmap emoticons hr pagebreak insertdatetime | link'

const unIndentTagRegex = /<img|<video|<audio|<object|<embed|<table/g


function initTinyMec(el, options = {}) {
    const defOptions = {
        selector: el,
        language:'zh_CN',
        menubar: true,
        automatic_uploads: true,
        images_upload_handler: uploadImages,
        file_picker_callback: file_picker_callback,
        file_picker_types: 'file',
        image_advtab: true,
        relative_urls: false,
        images_file_types: 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp',
        plugins: defaultPlugins,
        paste_preprocess: (plugin, args) => {
            // 粘贴link去除
            args.content = args.content.replace(/<\/?a.*?>/g, '')
        },
        paste_postprocess: (plugin, args) => {
            // 粘贴的内容，img,video,audio,object,embed,table增加no-indent
            const nodes = args.node.childNodes
            nodes.forEach(node => {
                if ((node.innerHTML && node.innerHTML.match(unIndentTagRegex)) && (node.classList && !node.classList.contains('no-indent'))) {
                    node.classList.add('no-indent')
                }
            })
        },
        // 工具栏固定
        toolbar_sticky: true,
        toolbar_sticky_offset: 0,
        toolbar_mode: 'wrap',
        // 自定义工具组
        toolbar_group: {
            align: {
                icon: 'alignleft',
                tooltip: '对齐',
                items: 'alignleft aligncenter alignright alignjustify'
            }
        },
        // 工具条
        toolbar: defaultToolbar,
        quickbars_selection_toolbar: 'bold italic | link h1 h2 h3  | blockquote quickimage quicktable | align',
        branding: false,
        min_height: 800
    }

    const lastOptions = Object.assign(defOptions, options)

    return tinymce.init(lastOptions)
}

function file_picker_callback(callback, value, meta) {
    console.info(value)
    console.info(meta)
    var filetype='.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4'

    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', filetype)
    input.click();

    input.onchange = function() {
        var file = this.files[0];

        doUpload(file).then(result => {
            if(result.code == 0) {
                callback(result.fileName, {text: result.originalFilename})
            } else {
                alert(result.msg)
            }
        }).catch(e => {
            $.modal.alertWarning(e);
        })
    }

}

// 自定义文件上传
function uploadImages(fileBlob) {
    const file = new File([fileBlob.blob()], fileBlob.filename())

    return new Promise((resolve, reject) => {
        if (file.size > 500 * 1024) {
            reject('文件上传失败: 图片大小不能超过500KB')
        } else {
            doUpload(file).then(uploadResult => {
                resolve(uploadResult.url)
            }).catch((e) => {
                // this.$message.error('文件上传失败' + e)
                reject('文件上传失败:' + e)
            })
        }
    })

}

function doUpload(file) {
    var data = new FormData();
    data.append("file", file);


    return new Promise((resolve, reject) => {
        $.ajax({
            type: "post",
            url: ctx + "common/upload",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(result) {
                console.info(result)
                if (result.code == web_status.SUCCESS) {
                    resolve(result)
                } else {
                    reject(result.msg);
                }
            },
            error: function(error) {
                $.modal.alertWarning("图片上传失败。");
            }
        });
    })
}